// Copyright 2024 awol2005ex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Authentication functions for kinit

use ascii::AsciiString;
use awol2005ex_kerbeiros::{TgtRequester, Credential};
use awol2005ex_kerberos_crypto::Key;
use std::net::{IpAddr, ToSocketAddrs};
use std::error::Error;
use crate::utils;

/// Perform kinit using password authentication
/// Simple implementation with basic string-to-key conversion
pub fn kinit_with_password(principal: &str, password: &str, kdc_ip: &str) -> Result<Credential, Box<dyn Error>> {
    println!("Performing kinit with password authentication...");
    println!("Principal: {}", principal);
    println!("KDC IP: {}", kdc_ip);
    
    // Parse the principal to extract realm and username
    let (username, realm) = utils::parse_principal(principal)?;
    
    // Parse KDC address - can be IP address or hostname
    let kdc_address: IpAddr = match kdc_ip.parse() {
        Ok(ip) => ip,
        Err(_) => {
            // Try to resolve hostname to IP address
            let kdc_socket = format!("{}:88", kdc_ip);
            match kdc_socket.to_socket_addrs() {
                Ok(mut addrs) => {
                    match addrs.next() {
                        Some(addr) => addr.ip(),
                        None => return Err(format!("Could not resolve KDC hostname: {}", kdc_ip).into()),
                    }
                }
                Err(e) => return Err(format!("Could not resolve KDC hostname '{}': {}", kdc_ip, e).into()),
            }
        }
    };
    
    // Prepare the arguments
    let realm_ascii = AsciiString::from_ascii(realm)
        .map_err(|e| format!("Invalid realm: {}", e))?;
    let username_ascii = AsciiString::from_ascii(username)
        .map_err(|e| format!("Invalid username: {}", e))?;
    
    // Use password directly as secret key (simplified approach)
    let user_key = Key::Secret(password.to_owned());
    
    // Create TGT requester and request TGT
    let tgt_requester = TgtRequester::new(realm_ascii, kdc_address);
    let credential = tgt_requester.request(&username_ascii, Some(&user_key))
        .map_err(|e| format!("TGT request failed: {}", e))?;
    
    println!("Successfully obtained TGT for {}", principal);
    Ok(credential)
}

/// Perform kinit using keytab file
pub fn kinit_with_keytab(keytab_path: &str, principal: &str, kdc_ip: &str) -> Result<Credential, Box<dyn Error>> {
    println!("Performing kinit with keytab...");
    println!("Keytab: {}", keytab_path);
    println!("Principal: {}", principal);
    println!("KDC IP: {}", kdc_ip);
    
    // Parse the principal to extract realm
    let (_, realm) = utils::parse_principal(principal)?;
    
    // Load the key from keytab
    let user_key = crate::keytab::load_key_from_keytab(keytab_path, principal)?;
    
    // Parse KDC address - can be IP address or hostname
    let kdc_address: IpAddr = match kdc_ip.parse() {
        Ok(ip) => ip,
        Err(_) => {
            // Try to resolve hostname to IP address
            let kdc_socket = format!("{}:88", kdc_ip);
            match kdc_socket.to_socket_addrs() {
                Ok(mut addrs) => {
                    match addrs.next() {
                        Some(addr) => addr.ip(),
                        None => return Err(format!("Could not resolve KDC hostname: {}", kdc_ip).into()),
                    }
                }
                Err(e) => return Err(format!("Could not resolve KDC hostname '{}': {}", kdc_ip, e).into()),
            }
        }
    };
    
    // Prepare the arguments
    let realm_ascii = AsciiString::from_ascii(realm)
        .map_err(|e| format!("Invalid realm: {}", e))?;
    let username_ascii = AsciiString::from_ascii(utils::get_username(principal)?)
        .map_err(|e| format!("Invalid username: {}", e))?;
    
    // Create TGT requester
    let tgt_requester = TgtRequester::new(realm_ascii, kdc_address);
    
    // Request the TGT
    let credential = tgt_requester.request(&username_ascii, Some(&user_key))
        .map_err(|e| format!("TGT request failed: {}", e))?;
    
    println!("Successfully obtained TGT for {}", principal);
    Ok(credential)
}